package org.example.exampreparationtreasure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.exampreparationtreasure.mapper.*;
import org.example.exampreparationtreasure.model.dto.DateRange;
import org.example.exampreparationtreasure.model.entity.Answer;
import org.example.exampreparationtreasure.model.entity.ExamRecord;
import org.example.exampreparationtreasure.model.entity.IncorrectQuestionRecord;
import org.example.exampreparationtreasure.model.vo.ReportExportRequest;
import org.example.exampreparationtreasure.service.LearningAnalysisService;
import org.example.exampreparationtreasure.model.entity.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 学习分析服务实现类
 * 提供学习数据分析的核心业务逻辑
 */
@Service
@RequiredArgsConstructor
public class LearningAnalysisServiceImpl implements LearningAnalysisService {
	private final ExamRecordMapper examRecordMapper;
	private final IncorrectQuestionRecordMapper incorrectMapper;
	private final QuestionCategoryMapper categoryMapper;
	private final UserMapper userMapper;

	/**
	 * 根据题目难度计算权重
	 * 用于加权计算准确率，难度越高权重越大
	 *
	 * @param difficulty 题目难度（难/中/易）
	 * @return 难度权重值
	 */
	private static double weightByDifficulty(String difficulty) {
		if ("难".equals(difficulty)) return 1.2;
		if ("中".equals(difficulty)) return 1.0;
		return 0.8;
	}

	/**
	 * 分析用户学习状态
	 * 通过用户的考试记录和答题记录，计算学习状态指标
	 *
	 * @param userId 用户ID
	 * @return 学习状态对象，包含准确率、平均分、答题总数等
	 */
	@Override
	public List<ExamRecord> getExamRecordsByUserId(Long userId) {
		try {
			System.out.println("=== 开始查询用户考试记录 ===");
			System.out.println("用户ID: " + userId);

			// 查询用户的考试记录
			System.out.println("步骤1: 查询用户考试记录");
			LambdaQueryWrapper<ExamRecord> examQuery = new LambdaQueryWrapper<>();
			examQuery.eq(ExamRecord::getUserId, userId);

			List<ExamRecord> examRecords = examRecordMapper.selectList(examQuery);
			System.out.println("查询到考试记录数量: " + examRecords.size());

			// 输出详细的考试记录信息
			for (ExamRecord record : examRecords) {
				System.out.println("考试记录详情: id=" + record.getExamRecordId() +
						", userId=" + record.getUserId() +
						", paperId=" + record.getPaperId() +
						", totalScore=" + record.getTotalScore() +
						", correctAnswers=" + record.getCorrectAnswers() +
						", totalQuestions=" + record.getTotalQuestions() +
						", startTime=" + record.getStartTime() +
						", endTime=" + record.getEndTime());
			}

			// 如果需要计算额外的统计信息，可以在这里添加
			if (!examRecords.isEmpty()) {
				System.out.println("步骤2: 计算统计信息");

				// 计算总考试次数
				int totalExams = examRecords.size();
				System.out.println("总考试次数: " + totalExams);

				// 计算平均分数
				double avgScore = examRecords.stream()
						.filter(er -> er.getTotalScore() != null)
						.mapToDouble(er -> er.getTotalScore().doubleValue())
						.average()
						.orElse(0.0);
				System.out.println("平均分数: " + avgScore);

				// 计算总答题数
				int totalAnswers = examRecords.stream()
						.filter(er -> er.getTotalQuestions() != null)
						.mapToInt(ExamRecord::getTotalQuestions)
						.sum();
				System.out.println("总答题数: " + totalAnswers);

				// 计算总正确数
				int totalCorrect = examRecords.stream()
						.filter(er -> er.getCorrectAnswers() != null)
						.mapToInt(ExamRecord::getCorrectAnswers)
						.sum();
				System.out.println("总正确数: " + totalCorrect);

				// 计算整体准确率
				double overallAccuracy = totalAnswers > 0 ? (double) totalCorrect / totalAnswers : 0.0;
				System.out.println("整体准确率: " + overallAccuracy);
			}

			System.out.println("=== 考试记录查询完成 ===");
			System.out.println("返回记录数量: " + examRecords.size());

			return examRecords;

		} catch (Exception e) {
			System.err.println("=== 查询考试记录时发生异常 ===");
			System.err.println("异常类型: " + e.getClass().getSimpleName());
			System.err.println("异常消息: " + e.getMessage());
			System.err.println("异常堆栈: ");
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 诊断用户薄弱点
	 * 通过错题记录分析用户的知识薄弱环节
	 *
	 * @param userId 用户ID
	 * @return 薄弱点诊断结果，包含薄弱分类ID列表
	 */
	@Override
	public List<IncorrectQuestionRecord> getIncorrectRecordsByUserId(Long userId) {
		// 查询用户的错题记录，按错误次数降序排列
		LambdaQueryWrapper<IncorrectQuestionRecord> query = new LambdaQueryWrapper<>();
		query.eq(IncorrectQuestionRecord::getUserId, userId)
				.orderByDesc(IncorrectQuestionRecord::getMistakeCount);

		return incorrectMapper.selectList(query);
	}

	@Override
	public List<QuestionCategory> getQuestionCategoriesByUserId(Long userId) {
		// 查询所有题目分类
		LambdaQueryWrapper<QuestionCategory> query = new LambdaQueryWrapper<>();
		query.orderByAsc(QuestionCategory::getSortOrder);

		return categoryMapper.selectList(query);
	}

	@Override
	public User generateUserReport(Long userId, ReportExportRequest request) {
		// 查询用户信息
		LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
		query.eq(User::getId, userId);

		return userMapper.selectOne(query);
	}
}